import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { submit as submitFun } from '../services/login';
import { setAuthority, setToken } from '../utils/authority';
import { getPageQuery } from '../utils/utils';
import { reloadAuthorized } from '../utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(submitFun, payload);
      yield put({
        type: 'changeLogin',
        payload: response,
      });
      // Login successfully
      if (response.code === 0) {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/workspace/statistics'));
      }else{
        yield put({
          type: 'loginError',
          payload: 'error',
        })
      }
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLogout',
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
  },

  reducers: {
    changeLogin(state, { payload }) {
      // Only 'admin' be allowed in setAuthority method, I'm confuse!!! (2018/10/11 by Jin)
      setAuthority('admin');
      setToken(payload.data.token);
      localStorage.setItem('name', payload.data.name);
      return {
        ...state,
        status: payload.code,
      };
    },
    loginError(state, { payload }){
      return{
        ...state,
        status: payload,
      }
    },
    changeLogout(state){
      setAuthority('guest');
      setToken('');
      return {
        ...state,
        status: undefined,
      }
    },
  },
};
